package common

import (
	"beesoft.ink/application/garage/app/g"
	"beesoft.ink/application/garage/app/model"
	"beesoft.ink/application/garage/app/model/common"
	"github.com/labstack/echo/v4"
)

var Garage = garage{}

type garage struct{}

func (r garage) Categories(ctx echo.Context, categoryType uint) []common.CategoryItem {
	res := []common.CategoryItem{}

	var items []model.Category
	g.DB().
		Where("type", categoryType).
		Find(&items)

	for _, item := range items {
		res = append(res, common.CategoryItem{
			Id:   item.Number,
			Name: item.Title,
		})
	}

	return res
}
func (r garage) Garages(ctx echo.Context) []common.GarageArea {
	res := make(map[uint]common.GarageArea)

	var areaList []model.Area
	g.DB().
		Where("type", 1).
		Find(&areaList)

	areas := map[uint]model.Area{}
	for _, item := range areaList {
		areas[item.ID] = item
	}

	var items []model.Garage
	g.DB().
		Find(&items)

	for _, item := range items {
		area := areas[item.AreaId]
		if temp, ok := res[area.ID]; ok {
			temp.Items = append(temp.Items, common.GarageItem{
				Id:   item.ID,
				Name: item.Title,
			})
			res[area.ID] = temp
		} else {
			res[area.ID] = common.GarageArea{
				Id:   area.ID,
				Name: area.Title,
				Items: []common.GarageItem{
					{
						Id:   item.ID,
						Name: item.Title,
					},
				},
			}
		}
	}

	var result []common.GarageArea
	for _, v := range res {
		result = append(result, v)
	}

	return result
}
